//
//  Problem1302.swift
//  TestProject
//
//  Created by 武侠 on 2021/6/8.
//  Copyright © 2021 zhulong. All rights reserved.
//

import UIKit

/*
 1302. 层数最深叶子节点的和
 给你一棵二叉树的根节点 root ，请你返回 层数最深的叶子节点的和 。
 示例 1：
     输入：root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
     输出：15
 示例 2：
     输入：root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
     输出：19

 提示：
     树中节点数目在范围 [1, 104] 之间。
     1 <= Node.val <= 100
 */
@objcMembers class Problem1302: NSObject {
    func solution() {
        let root = TreeNode(1)
        root.left = TreeNode(2)
        root.left?.left = TreeNode(4)
        root.left?.right = TreeNode(5)
        root.left?.left?.left = TreeNode(7)
        
        root.right = TreeNode(3)
        root.right?.right = TreeNode(6)
        root.right?.right?.right = TreeNode(8)
        
        print(deepestLeavesSum(root))
    }
    
    func deepestLeavesSum(_ root: TreeNode?) -> Int {
        if root == nil {
            return 0
        }
        var list:[TreeNode?] = [root]
        while list.isEmpty == false {
            // 判断是否有下一层
            var hasNext = false
            for node in list {
                if node?.left != nil || node?.right != nil {
                    hasNext = true
                    break
                }
            }
            
            if hasNext == false {
                var sum = 0
                for node in list {
                    sum += node!.val
                }
                return sum
            } else {
                var n = list.count
                while n > 0 {
                    let node = list.removeFirst()
                    if node?.left != nil {
                        list.append(node?.left)
                    }
                    if node?.right != nil {
                        list.append(node?.right)
                    }
                    n -= 1
                }
            }
        }
        
        return 0
    }
}
